#include "H264Decoder.h"
#include <opencv2/imgcodecs.hpp>

#include "utils.h"

#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

unsigned char buf[37*1000*1000];//should be max enough
//

int main2(int argc , char * argv[]) {
    H264Decoder decoder;
    const char * fname = "/home/app/fzw/hwout.264/00000001.raw";
    if (argc==2) {
        fname = argv[1];
    }
    cout << fname << endl;
    std::ifstream fin(fname, std::ios_base::binary);
    fin.seekg(0, std::ios::end);
    int len = fin.tellg();
    fin.seekg(0, std::ios::beg);

    fin.read((char *) buf, len);
    memset(buf+len, 0, 4);
    decoder.decode(buf, len);
    decoder.play();
    vector<int> compression_params;
    compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
    compression_params.push_back(90);

    cv::imwrite("/home/app/fzw/hwh264.jpg", decoder.getMat(), compression_params);
    
}

bool str_compar(string a , string b) {
    return a<b;
}

int main(int argc , char * argv[]) {
    const char * winname = "H265 Decode";
    H264Decoder *decoder = new H264Decoder(winname, AV_CODEC_ID_H265);
    std::string img_dir = "/home/app/fzw/hwout.265";
    if (argc>=2) {
        img_dir = std::string(argv[1]);
    }
    cout << img_dir << endl;

    if (argc>=3) {
        cv::startWindowThread();
        cv::namedWindow(winname);
    }

    std::vector<std::string> file_names;
    if (read_files_in_dir(img_dir.c_str(), file_names) < 0) {
        std::cerr << "read_files_in_dir failed." << std::endl;
        return -1;
    }
    sort(file_names.begin(), file_names.end(), str_compar);

    int fcount = 0;
    for (int f = 0; f < (int)file_names.size(); f++) {
        fcount++;

        string fname = img_dir + "/" + file_names[f];
        std::ifstream fin(fname, std::ios_base::binary);
        fin.seekg(0, std::ios::end);
        int len = fin.tellg();
        fin.seekg(0, std::ios::beg);

        if (len+4>sizeof(buf)) {
            cout<< fname << "size(" << len << ") too large\n";
            continue;
        }
        cout << fcount << ":"<< fname << ":size " << setw(8) << right << len << endl;

        fin.read((char *) buf, len);
        memset(buf+len, 0, 4);
        decoder->decode(buf, len);
        if ( argc>=3 ) {
            decoder->play(1);
        } else {
            vector<int> compression_params;
            compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
            compression_params.push_back(90);
            // decoder->getMat();
            cv::imwrite("/home/app/fzw/hwout/"+file_names[f]+".jpg", decoder->getMat(), compression_params);
        }
    }
    delete decoder;
    cv::destroyAllWindows();
    return 0;
}

